<template>
  <div class="coupon-center-management">
    <div class="page-header">
      <h2>领券中心管理</h2>
      <p class="page-desc">管理APP领券中心的展示内容、活动设置和用户领取情况</p>
    </div>



    <!-- 功能区域 -->
    <el-tabs v-model="activeTab" class="function-tabs">
      <!-- 优惠券管理 -->
      <el-tab-pane label="优惠券管理" name="coupon">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>领券中心优惠券管理</span>
              <div class="header-actions">
                <el-button @click="refreshData" :loading="loading">
                  <el-icon><Refresh /></el-icon>
                  刷新优惠券数据
                </el-button>
                <el-button type="primary" @click="openCouponDialog">添加优惠券</el-button>
              </div>
            </div>
          </template>
          
          <el-table :data="couponList" style="width: 100%">
            <el-table-column prop="position" label="排序位置" width="100" align="center" />
            <el-table-column prop="couponName" label="优惠券名称" />
            <el-table-column prop="couponType" label="优惠券类型">
              <template #default="scope">
                <el-tag :type="getCouponTypeTag(scope.row.couponType)">
                  {{ getCouponTypeName(scope.row.couponType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="discount" label="优惠内容" />
            <el-table-column prop="validPeriod" label="有效期" />
            <el-table-column prop="applicableSites" label="适用站点" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getStatusTag(scope.row.status)">
                  {{ getStatusName(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="editCoupon(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCoupon(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>


      </el-tabs>

      <!-- 优惠券编辑对话框 -->
      <el-dialog v-model="couponDialog.visible" :title="couponDialog.title" width="600px">
        <el-form :model="couponDialog.form" :rules="couponDialog.rules" ref="couponFormRef" label-width="100px">
          <el-form-item label="排序位置" prop="position">
            <el-input-number 
              v-model="couponDialog.form.position" 
              :min="1" 
              placeholder="请输入排序位置"
              style="width: 200px;"
            />
            <div class="form-tip">位置数字越小，在领券中心显示越靠前</div>
          </el-form-item>
          
          <el-form-item label="选择优惠券" prop="couponId">
            <el-select 
              v-model="couponDialog.form.couponId" 
              placeholder="请选择优惠券"
              style="width: 100%;"
              filterable
              @change="onCouponSelect"
            >
              <el-option 
                v-for="item in availableCoupons" 
                :key="item.id" 
                :label="`${item.name} (${item.type})`" 
                :value="item.id" 
              >
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <span>{{ item.name }}</span>
                  <el-tag size="small" :type="getCouponTypeTag(item.type)">{{ item.type }}</el-tag>
                </div>
              </el-option>
            </el-select>
            <div class="form-tip">从优惠券管理页面获取的优惠券列表，支持搜索筛选</div>
          </el-form-item>
          
          <el-form-item label="优惠券类型">
            <el-input v-model="couponDialog.form.couponType" readonly style="width: 100%;" />
            <div class="form-tip">自动从优惠券管理页面获取</div>
          </el-form-item>
          
          <el-form-item label="优惠内容">
            <el-input v-model="couponDialog.form.discount" readonly style="width: 100%;" />
            <div class="form-tip">自动从优惠券管理页面获取</div>
          </el-form-item>
          
          <el-form-item label="有效期">
            <el-input v-model="couponDialog.form.validPeriod" readonly style="width: 100%;" />
            <div class="form-tip">自动从优惠券管理页面获取</div>
          </el-form-item>
          
          <el-form-item label="适用站点">
            <el-input v-model="couponDialog.form.applicableSites" readonly style="width: 100%;" />
            <div class="form-tip">自动从优惠券管理页面获取</div>
          </el-form-item>
          
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="couponDialog.form.status">
              <el-radio label="active">启用</el-radio>
              <el-radio label="inactive">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="couponDialog.visible = false">取消</el-button>
            <el-button type="primary" @click="saveCoupon">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { useCouponStore } from '@/store/couponStore'

// 使用共享的优惠券存储
const couponStore = useCouponStore()

// 当前激活的标签页
const activeTab = ref('coupon')

// 优惠券列表 - 使用共享存储
const couponList = computed(() => couponStore.getCouponCenterList())

// 可用优惠券列表（从优惠券管理页面获取，排除已添加的）
const availableCoupons = computed(() => couponStore.getAvailableCouponsForCenter)



// 优惠券对话框
const couponDialog = reactive({
  visible: false,
  title: '添加优惠券',
  form: {
    id: 0,
    position: 1,
    couponId: '',
    couponName: '',
    couponType: '',
    discount: '',
    validPeriod: '',
    applicableSites: '',
    status: 'active' as 'active' | 'inactive'
  },
  rules: {
    position: [{ required: true, message: '请输入排序位置', trigger: 'blur' }],
    couponId: [{ required: true, message: '请选择优惠券', trigger: 'change' }]
  }
})

// 加载状态
const loading = ref(false)

// 表单引用
const couponFormRef = ref()

// 获取优惠券类型标签样式
const getCouponTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    '满减券': 'success',
    '折扣券': 'warning',
    '包邮券': 'info',
    '无门槛券': 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取优惠券类型名称（直接返回，因为已经是中文名称）
const getCouponTypeName = (type: string) => {
  return type || '未知'
}

// 获取状态标签样式
const getStatusTag = (status: string) => {
  const statusMap: Record<string, string> = {
    active: 'success',
    inactive: 'info',
    expired: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态名称
const getStatusName = (status: string) => {
  const statusMap: Record<string, string> = {
    active: '启用',
    inactive: '停用',
    expired: '已过期'
  }
  return statusMap[status] || '未知'
}

// 打开优惠券对话框
const openCouponDialog = () => {
  couponDialog.title = '添加优惠券'
  couponDialog.form = {
    id: 0,
    position: getNextPosition(),
    couponId: '',
    couponName: '',
    couponType: '',
    discount: '',
    validPeriod: '',
    applicableSites: '',
    status: 'active' as 'active' | 'inactive'
  }
  couponDialog.visible = true
}

// 获取下一个可用位置
const getNextPosition = () => {
  const positions = couponList.value.map((item: any) => item.position)
  return Math.max(...positions, 0) + 1
}

// 编辑优惠券
const editCoupon = (coupon: any) => {
  couponDialog.title = '编辑优惠券'
  couponDialog.form = { 
    id: coupon.id,
    position: coupon.position,
    couponId: coupon.couponId,
    couponName: coupon.couponName,
    couponType: coupon.couponType,
    discount: coupon.discount,
    validPeriod: coupon.validPeriod,
    applicableSites: coupon.applicableSites,
    status: coupon.status
  }
  couponDialog.visible = true
}

// 删除优惠券
const deleteCoupon = async (coupon: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除优惠券"${coupon.couponName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 使用共享存储删除优惠券
    couponStore.removeFromCouponCenter(coupon.id)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

// 优惠券选择处理
const onCouponSelect = (couponId: string) => {
  const selectedCoupon = availableCoupons.value.find((item: any) => item.id === couponId)
  if (selectedCoupon) {
    couponDialog.form.couponName = selectedCoupon.name
    couponDialog.form.couponType = selectedCoupon.type
    
    // 根据优惠券类型生成优惠内容描述
    let discount = ''
    if (selectedCoupon.type === '满减券') {
      discount = `满${selectedCoupon.minAmount}减${selectedCoupon.amount}`
    } else if (selectedCoupon.type === '折扣券') {
      discount = `满${selectedCoupon.minAmount}享${selectedCoupon.discountRate}折`
      if (selectedCoupon.maxDiscount) {
        discount += `，最高减${selectedCoupon.maxDiscount}`
      }
    } else if (selectedCoupon.type === '包邮券') {
      discount = `免运费(${couponStore.getLogisticsName(selectedCoupon.logistics || 'ems')})`
    } else if (selectedCoupon.type === '无门槛券') {
      discount = `无门槛减${selectedCoupon.amount}`
    }
    
    couponDialog.form.discount = discount
    couponDialog.form.validPeriod = selectedCoupon.validDesc || ''
    couponDialog.form.applicableSites = couponStore.getSitesDescription(selectedCoupon.sites)
  }
}

// 保存优惠券
const saveCoupon = async () => {
  try {
    await couponFormRef.value?.validate()
    
    // 检查位置是否重复
    const existingCoupon = couponList.value.find((item: any) => 
      item.position === couponDialog.form.position && item.id !== couponDialog.form.id
    )
    if (existingCoupon) {
      ElMessage.error('排序位置已被占用，请选择其他位置')
      return
    }
    
    // 实际项目中应该调用保存API
    if (couponDialog.title === '添加优惠券') {
      const newCoupon = {
        id: Date.now(),
        position: couponDialog.form.position,
        couponId: couponDialog.form.couponId,
        couponName: couponDialog.form.couponName,
        couponType: couponDialog.form.couponType,
        discount: couponDialog.form.discount,
        validPeriod: couponDialog.form.validPeriod,
        applicableSites: couponDialog.form.applicableSites,
        status: couponDialog.form.status
      }
      try {
        couponStore.addToCouponCenter(
          couponDialog.form.couponId,
          couponDialog.form.position
        )
        ElMessage.success('优惠券添加成功')
      } catch (error: any) {
        ElMessage.error(error.message || '添加失败')
        return
      }
    } else {
      // 编辑优惠券状态
      couponStore.updateCouponCenterStatus(couponDialog.form.id, couponDialog.form.status)
      ElMessage.success('优惠券更新成功')
    }
    
    couponDialog.visible = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}



// 刷新数据
const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据已刷新')
  }, 500)
}

// 组件挂载后初始化数据
onMounted(() => {
  // 数据已通过computed自动获取，无需手动加载
})
</script>

<style scoped>
.coupon-center-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-desc {
  margin: 0;
  color: #909399;
  font-size: 14px;
}



.function-tabs {
  margin-top: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.coupon-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}
</style>
